<!--
 * @Description: 收货单详情
 * @Author: wning
 * @Date: 2023-03-22 16:48:18
 * @LastEditors: wning
 * @LastEditTime: 2023-03-31 11:26:43
-->

<template>
  <x-sub-page :content="'收货单详情'" @goBack="handleBack">
    <div class="pricing-detail" v-loading="pageLoading">
      <div class="form-components">
        <div class="panl-title">
          <span>基础信息</span>
        </div>
      </div>
      <el-descriptions
        direction="vertical"
        :column="3"
        label-class-name="title-style"
        content-class-name="content-style"
      >
        <el-descriptions-item :label="$t('shipmentCollaboration.form.deliveryNoteNumber')">{{
          dataForm.number
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('shipmentCollaboration.form.state')">{{
          selectDictLabel(dictOptions['srm_delivery_note.state'], dataForm.state)
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('shipmentCollaboration.form.consignor')">{{
          dataForm.consignor
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('shipmentCollaboration.form.consignorPhone')">{{
          dataForm.consignorPhone
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('shipmentCollaboration.form.deliveryMethod')">{{
          selectDictLabel(dictOptions['srm_delivery_note.delivery_method'], dataForm.deliveryMethod)
        }}</el-descriptions-item>
        <!-- 自主 -->
        <template v-if="dataForm.deliveryMethod === 'self'">
          <el-descriptions-item :label="$t('shipmentCollaboration.form.shipper')">{{
            dataForm.shipper
          }}</el-descriptions-item>
          <el-descriptions-item :label="$t('shipmentCollaboration.form.shipperPhone')">{{
            dataForm.shipperPhone
          }}</el-descriptions-item>
        </template>
        <!-- 物流 -->
        <template v-else>
          <el-descriptions-item :label="$t('shipmentCollaboration.form.logisticalCompany')">{{
            selectDictLabel(dictOptions['srm_delivery_note.logistical_company'], dataForm.logisticalCompany)
          }}</el-descriptions-item>
          <el-descriptions-item :label="$t('shipmentCollaboration.form.logisticalNumber')">{{
            dataForm.logisticalNumber
          }}</el-descriptions-item>
        </template>

        <el-descriptions-item :label="$t('shipmentCollaboration.form.deliveryDate')">{{
          replaceDateTime(dataForm.deliveryDate)
        }}</el-descriptions-item>
        <el-descriptions-item :label="$t('shipmentCollaboration.form.arrivalDate')">{{
          replaceDateTime(dataForm.arrivalDate)
        }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="margin-top" :column="1" direction="vertical">
        <el-descriptions-item :label="'附件'">
          <x-upload
            ref="fileUpload"
            :fileSize="30"
            :span="6"
            :limit="9"
            :isFileRemark="false"
            :edit-flag="false"
            :old-file-list="dataForm.deliveryNoteFileList"
            :file-type="['jpg', 'jpeg', 'png', 'ppt', 'pptx', 'pdf', 'xls', 'xlsx', 'doc', 'docx']"
            :tips="'支持上传PPT/PDF/EXCEL/WORD/PNG/JPG形式文件, 最多9个, 附件大小不超过30MB.'"
          >
          </x-upload>
        </el-descriptions-item>
      </el-descriptions>

      <div class="form-components">
        <div class="panl-title">
          <span>送货物料明细</span>
        </div>
      </div>
      <el-form ref="dataForm" :model="dataForm" :rules="dataRule">
        <x-table
          ref="tableCom"
          :isPagination="false"
          :data-source="dataForm.deliveryNoteDetailList"
          :row-key="'id'"
          @on-selection-change="handleSelectionChange"
          :height="(dataForm.deliveryNoteDetailList.length > 5 ? dataForm.deliveryNoteDetailList.length : 5) * 42 + 50"
        >
          <template v-if="isDetail">
            <el-table-column type="selection" width="55" />
          </template>
          <template v-else>
            <el-table-column type="index" fixed width="55" label="序号" />
          </template>
          <el-table-column
            v-for="(item, index) in columns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width"
            :min-width="item.minWidth || '-'"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <span v-if="item.prop === 'state'">{{
                selectDictLabel(dictOptions['srm_delivery_note.state'], scope.row.state)
              }}</span>
              <span v-else-if="item.prop === 'billState'"
                >{{ selectDictLabel(dictOptions['srm_delivery_note_detail.bill_state'], scope.row.billState) }}
              </span>
              <span v-else-if="item.prop === 'deliveryDate'">
                {{ replaceDateTime(scope.row[item.prop]) }}
              </span>
              <span v-else-if="item.prop === 'supplierName'">{{ dataForm.supplierName | emptyVal }}</span>
              <span v-else-if="item.prop === 'materialUnit'">{{selectDictLabel(dictOptions['srm_material.material_unit'], scope.row[item.prop])}}</span>
              <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="receivedQuantity"
            :label="$t('shipmentCollaboration.column.realityReceivedQuantity')"
            minWidth="140"
            fixed="right"
          >
            <template slot="header" v-if="isDetail">
              <span class="headerRequire">{{ $t('shipmentCollaboration.column.realityReceivedQuantity') }}</span>
            </template>
            <div class="item" slot-scope="scope">
              <el-form-item
                :prop="`deliveryNoteDetailList.${scope.$index}.${['receivedQuantity']}`"
                :rules="dataRule['receivedQuantity']"
              >
                <el-input-number
                  v-if="isDetail && (scope.row.state === 1 || scope.row.state === 2)"
                  v-model="scope.row.receivedQuantity"
                  placeholder="请输入"
                  size="small"
                  :min="0"
                  :max="99999999"
                  :precision="0"
                  :controls="false"
                ></el-input-number>
                <span v-else>{{ scope.row.receivedQuantity | emptyVal }}</span>
              </el-form-item>
            </div>
          </el-table-column>
        </x-table>
      </el-form>
    </div>
    <fixed-btn-area>
      <el-button @click="handleBack"> {{ isDetail ? $t('common.cancel') : $t('common.goBack') }} </el-button>
      <el-button
        v-if="isDetail"
        type="primary"
        v-hasPermi="['srm:deliveryNote:receive']"
        @click="handleReceive"
        :loading="pageLoading"
      >
        {{ '确认收货' }}
      </el-button>
    </fixed-btn-area>
  </x-sub-page>
</template>

<script>
  import { QueryDictMixin, cloneDeep, selectDictLabel, throttle, replaceDateTime } from '@package/utils'
  import {
    apiGetDeliveryDetail,
    apiDeliveryNoteReceive
  } from '@/modules/shipmentCollaboration/api/receivingManagement.js'
  import { detailColumns } from '@/modules/shipmentCollaboration/config/wholeOrderReceipt.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    name: 'ReceivingDetail',
    mixins: [QueryDictMixin],
    inject: ['closePages'],
    data() {
      return {
        id: '',
        pageLoading: false,
        columns: detailColumns,
        dataForm: {
          title: '',
          realName: '',
          mobile: '',
          remark: '',
          type: '',
          deliveryNoteDetailList: [],
          deliveryNoteFileList: []
        },
        isDetail: true,
        dataRule: {
          receivedQuantity: [{ required: true, message: '请输入', trigger: 'blur' }]
        },
        selectData: [],
        srmDictKeys: [
          'srm_delivery_note.delivery_method',
          'srm_delivery_note.logistical_company',
          'srm_delivery_note.state',
          'srm_delivery_note_detail.bill_state',
          'srm_material.material_unit'
        ]
      }
    },
    mounted() {
      const {
        query: { id, isDetail }
      } = this.$route
      this.id = id
      this.isDetail = isDetail
      this.initDictConfig()
      this.getInfo(id)
      console.log(this.dictOptions)
    },
    methods: {
      replaceDateTime,
      selectDictLabel,
      // 获取详情
      async getInfo(id) {
        const { data, code } = await apiGetDeliveryDetail(id)
        if (code === EnumApiCode.Success) {
          this.$nextTick(() => {
            this.dataForm = Object.assign(this.dataForm, cloneDeep(data))
          })
        }
      },
      // 多行选中
      handleSelectionChange(rows) {
        this.selectData = rows
      },
      // 确认收货
      handleReceive() {
        this.$confirm('是否确认收货所有发货单物料，如需单物料确认收货，请勾选物料再确认收货', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 确认收货所有发货单物料
          if (this.selectData.length === this.dataForm.deliveryNoteDetailList.length || this.selectData.length === 0) {
            this.handleSubmit()
          } else {
            this.handleSubmitOnly()
          }
        })
      },
      handleSubmit: throttle(function () {
        this.$refs.dataForm.validate(async (valid) => {
          if (valid) {
            this.pageLoading = true
            const param = {
              id: this.id,
              deliveryNoteDetailList: this.dataForm.deliveryNoteDetailList
            }
            try {
              const { code, msg } = await apiDeliveryNoteReceive(param)
              this.pageLoading = false
              if (code === EnumApiCode.Success) {
                this.$message.success('确认收货成功')
                this.handleBack()
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.pageLoading = false
            }
          } else {
            return false
          }
        })
      }, 1000),
      async handleSubmitOnly() {
        const deliveryNoteDetailList = this.selectData
        const flag = this.selectData.findIndex((item) => {
          return !item.receivedQuantity
        })

        if (flag === -1) {
          this.pageLoading = true
          const param = {
            id: this.$route.query.id,
            deliveryNoteDetailList: this.selectData
          }
          try {
            const { code, msg } = await apiDeliveryNoteReceive(param)
            this.pageLoading = false
            if (code === EnumApiCode.Success) {
              this.$message.success('确认收货成功')
              this.handleBack()
            } else {
              this.$message.error(msg)
            }
          } finally {
            this.pageLoading = false
          }
        } else {
          return false
        }
      },
      handleBack() {
        this.$router.go(-1)
        this.closePages()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .pricing-detail {
    height: calc(100% - 71px);
    padding: 0 20px;
    overflow: auto;
    .panl-title {
      height: 45px;
      // margin: 0 16px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ededed;
      margin-bottom: 16px;
      span {
        display: inline-block;
        height: 22px;
        line-height: 22px;
        color: #171c26;
        border-left: 2px solid #4474f6;
        padding-left: 12px;
        font-size: 16px;
        font-weight: 700;
      }
    }
    ::v-deep .title-style {
      color: #707683;
      font-size: 14px;
    }
    ::v-deep .content-style {
      padding-bottom: 20px;
      color: #333;
      font-size: 14px;
    }
    .table-title {
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      color: #707683;
      font-weight: normal;
    }
    ::v-deep .el-table .el-table__row {
      height: 56px;
    }

    // ::v-deep .el-table__row .el-form-item {
    //   margin-bottom: 0;
    // }
    ::v-deep .el-table__row .el-form-item__error {
      padding-top: 0;
    }
    ::v-deep .el-table__row .el-form-item__content {
      line-height: 32px;
    }
    .headerRequire:before {
      content: '*';
      color: #f56c6c;
      margin-right: 4px;
    }
    ::v-deep .el-table__cell {
      .el-input-number--small {
        width: 100%;
        height: 28px;
        .el-input--small {
          height: inherit;

          input {
            height: inherit;
            width: 100%;
            text-align: left;
          }
        }
      }
    }
  }
</style>
